package com.flashcash.kotlin.auth.accountKit

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.util.Base64
import com.flashcash.solu.BuildConfig
import com.flashcash.solu.R
import com.facebook.accountkit.AccountKit
import com.facebook.accountkit.Account
import com.facebook.accountkit.AccountKitError
import com.facebook.accountkit.AccountKitLoginResult
import com.facebook.accountkit.internal.InternalAccountKitError
import com.facebook.accountkit.ui.AccountKitActivity
import com.facebook.accountkit.ui.AccountKitConfiguration
import com.facebook.accountkit.ui.LoginType
import com.x.leo.apphelper.log.XLog

import com.facebook.accountkit.AccountKitCallback





/**
 * Created by XLEO on 2018/3/5.
 */
object AccountKitLoginManager {
    var callBack: CallBack? = null
    private var authState: String? = null
    private val stateListener: BroadcastReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                XLog.i("onReceive", 10)
                if (intent == null) {
                    return
                }
                val action = intent.action
                if (ACTION_UPDATE.contentEquals(action!!)) {
                    val event = intent.getSerializableExtra(EXTRA_EVENT)
                    XLog.i("state:" + event?.toString(), 10)
                    try {
                        val clazz = Class.forName("com.facebook.accountkit.ui.LoginFlowBroadcastReceiver\$Event")
                        val clazzObj = clazz.cast(event)
                        val ordinalM = java.lang.Enum::class.java.getDeclaredMethod("ordinal")
                        val i = ordinalM.invoke(clazzObj) as Int
                        when (i) {
                            1 -> {
                                XLog.i("state:1", 10)
                            }
                            else -> XLog.i("state:" + i, 10)
                        }
                    } catch (e: Exception) {
                        XLog.e("class cast exception:", e, 100)
                    }

                }
            }
        }
    }

    fun unbindAccountKitStateListener(act: Activity) {
        // LocalBroadcastManager.newInstance(act.applicationContext).unregisterReceiver(stateListener)
    }

    private val EXTRA_EVENT = "LoginFlowBroadcastReceiver.extra_event"
    private val ACTION_UPDATE = "LoginFlowBroadcastReceiver.action_update"
    fun bindAccountKitStateListener(act: Activity) {
//        val filter = IntentFilter()
//        filter.addAction(ACTION_UPDATE)
//        filter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY
//        LocalBroadcastManager.newInstance(act.applicationContext).registerReceiver(stateListener, filter)
    }

    private fun generateRandomString(): String {
        val randomNum = Math.random()
        val currentTime = System.currentTimeMillis()
        val defaultKey = BuildConfig.APPLICATION_ID
        return try {
            String(Base64.encode(StringBuilder(defaultKey).append(randomNum).append(currentTime).toString().toByteArray(), Base64.DEFAULT))
        } catch (e: Exception) {
            "test_info"
        }
    }

    fun phoneLogin(act: Activity): Intent {
        checkSession()
        val intent = Intent(act, AccountKitActivity::class.java)


        // or .ResponseType.TOKEN
        // ... perform additional configuration ...
        authState = generateRandomString()
        val smsWhiteList = BuildConfig.FB_SMS_WHIT_LIST
        val configuration =
                AccountKitConfiguration.AccountKitConfigurationBuilder(
                        LoginType.PHONE,
                        AccountKitActivity.ResponseType.CODE)
                        .setInitialAuthState(authState)
                        .setFacebookNotificationsEnabled(true)
                        .setUIManager(CustomerUIManager(R.style.accountKitLoginStyle))
                        .setSMSWhitelist(smsWhiteList)
                        .setDefaultCountryCode(BuildConfig.FB_DEFAULT_COUNTRY_CODE)
                        .build()

        intent.putExtra(
                AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
                configuration)




        AccountKit.getCurrentAccount(object : AccountKitCallback<Account> {
            override fun onSuccess(account: Account) {
                // Get Account Kit ID
                //val accountKitId = account.getId()

                // Get phone number
                val phoneNumber = account.getPhoneNumber()
                val phoneNumberString = phoneNumber.toString()


            }

            override fun onError(error: AccountKitError) {
                // Handle Error

            }
        })



        return intent
    }

    private fun checkSession() {
        val accessToken = AccountKit.getCurrentAccessToken()

        if (accessToken != null) {
            //Handle Returning User
            AccountKit.logOut()
        } else {
            //Handle new or logged out user
        }
    }

    fun handleResult(data: Intent, act: Activity) {
        // confirm that this response matches your request
        val loginResult = data.getParcelableExtra<AccountKitLoginResult>(AccountKitLoginResult.RESULT_KEY)
        val toastMessage: String



        when {
            loginResult == null -> {

                toastMessage = "null login result"
                val errorResult = AccountKitError(AccountKitError.Type.ARGUMENT_ERROR, InternalAccountKitError(800, toastMessage))
                callBack?.onError(errorResult)
            }
            loginResult.error != null -> {
                toastMessage = loginResult.error!!.errorType.message
                callBack?.onError(loginResult.error)
            }
            loginResult.wasCancelled() -> {
                toastMessage = "Login Cancelled"
                callBack?.onCancel(loginResult)

                // notify LoginInterceptor
                LoginEventBus.postCancel()
            }
            else -> {


                XLog.i("local auth state:" + authState, 10)
                XLog.i("server auth state:" + loginResult.finalAuthorizationState, 10)
                toastMessage = if (loginResult.accessToken != null) {
                    "Success:" + loginResult.accessToken!!.accountId
                } else {
                    String.format(
                            "Success:%s...",
                            loginResult.authorizationCode!!.substring(0, 10))
                }


                // If you have an authorization code, retrieve it from
                // loginResult.getAuthorizationCode()
                // and pass it to your server and exchange it for an access token.

                // Success! Start your next activity...
                if (TextUtils.equals(authState?.trim()?.replace("\n", ""), loginResult.finalAuthorizationState?.trim()?.replace("\n", ""))) {
                    callBack?.onSuccess(loginResult)
                } else {
                    callBack?.onError(AccountKitError(AccountKitError.Type.ARGUMENT_ERROR, InternalAccountKitError(805, "error auth code")))
                }
            }
        }

        XLog.i("login result:" + toastMessage, 10)
    }

    interface CallBack {
        fun onError(error: AccountKitError?)
        fun onSuccess(loginResult: AccountKitLoginResult)
        fun onCancel(loginResult: AccountKitLoginResult)
    }
}